import logging
import json
import time
from redis import StrictRedis
from datetime import datetime
from django.conf import settings
from preprocessor.preprocessor import EventPreprocessor
from common.es_core.es_interface import es_search_interface


_LOGGER = logging.getLogger(__name__)


class MFPayEventPreprocessor(EventPreprocessor):
    """ 秒付 Preprocessor """
    def __init__(self, topic, add_prefix=True,
                 redis_conf_url=settings.GENERAL_REDIS):
        super().__init__(topic, add_prefix)
        self.redis = StrictRedis.from_url(redis_conf_url, charset="utf-8", decode_responses=True)

    def _mch_event_handler(self):
        mch_id = self.event_data['_mch_id']
        mch_item = self.redis.get(mch_id)
        if not mch_item:
            query_dsl = {
                "query": {
                    "bool": {"filter": [{"term": {"mch_create_mch_id": mch_id}},
                                        {"term": {"_event_id": "mch_create"}}]}
                },
                "size": 1
            }
            res = es_search_interface(self.topic, query_dsl)
            assert res['hits']['total'] == 1, '数据异常'
            mch_item = res['hits']['hits'][0]['_source']
            self.redis.set(mch_id, json.dumps(mch_item))
        else:
            mch_item = json.loads(mch_item)
        self.event_data['_mch_type'] = mch_item['mch_create_mch_type']

    def _agency_recharge_success_handler(self):
        self.event_data['_mch_type'] = 1

    def _user_event_handler(self):
        query_dsl = {
            "query": {
                "bool": {
                    "filter": [
                        {"term": {"_user_id": self.event_data['_user_id']}},
                        {"term": {"_event_id": 'user_recharge_create'}}
                    ]
                }
            },
            "size": 1,
            "sort": [
                {"_event_time": {"order": "asc"}}
            ]
        }
        res = es_search_interface(self.topic, query_dsl)
        if not res['hits']['total']:
            self.event_data['first_create_recharged_at'] = time.time()
            self.event_data['first_recharge_days'] = 0
        else:
            event_datetime = datetime.fromtimestamp(self.event_data['_event_time'])
            event_date = event_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
            first_recharge_datetime = datetime.fromtimestamp(res['hits']['hits'][0]['_source']['_event_time'])
            first_recharge_date = first_recharge_datetime.replace(hour=0, minute=0, second=0, microsecond=0)
            self.event_data['_first_recharge_days'] = (event_date - first_recharge_date).days
            self.event_data['_first_create_recharged_at'] = int(first_recharge_datetime.timestamp())

    def handle(self, event_data):
        self.event_data = event_data
        event_id = self.event_data['_event_id']
        if '_user_id' in self.event_data:
            self._user_event_handler()
        self.add_event_prefix()
        if '_mch_id' in self.event_data:
            self._mch_event_handler()
        if event_id == 'agency_recharge_success':
            self._agency_recharge_success_handler()
        return self.event_data
